/**
 * 生成指定长度的随机数
 * @param { number } length
*/
function generateRandomString(length) {  
    var result = ''
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    var charactersLength = characters.length
    for ( var i = 0; i < length; i++ ) {  
        result += characters.charAt(Math.floor(Math.random() * charactersLength))
    }  
    return result
}

/**
 * 日期格式化
*/
function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(/-/gm, '/').replace('T', ' ').replace(/\.[\d]{3}/gm, '')
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 获取开始结束时间
*/
function getTodayTimestamps() {
  const now = new Date();
  const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)
  const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999)

  return {
	startTime: startOfDay.getTime(),
	endTime: endOfDay.getTime()
  }
}
	
function api() {
	const unicloud = uniCloud.database()
	const isCheckToken = function (uniIDIns, token) {
		return new Promise((resolve, reject) => {
			uniIDIns.checkToken(token).then(res => {
				// console.log(`code:${res.code},msg:${res.errMsg}`);
				if(res.code === 30203 || res.code === 30202) {
					reject({ code: 401, msg: '登录状态失效，token已过期' })
				} else {
					resolve(res)
				}
			})
		})
	}
	
	const formatPrice = function (price) {
		return price.toFixed(2)
	}
	/**
	 * 添加账单信息
	 * @param { string } _id 账户id
	 * @param { string } refund 还款账户
	 * @param { string } transactionType 收入: 0 支出: 1 还款: 2
	 * @param { number } amount 金额
	 * 收入: amount + balance
	 * 支出: balance - amount
	 * 还款: (支出账户: balance - amount)(还款账户: balance + amount  paidPrice - amount)
	*/
	const addAccount = function (data, accountData) {
		return new Promise((resolve, reject) => {
			if(data.transactionType === '0') {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const result = {}
						result.balance = (Number(obj.balance) + Number(data.amount)).toFixed(2)
						return unicloud.collection('account').where({ _id: data.accountId }).update(result)
					} else {
						reject('无支出账户信息')
					}
				}).then(() => resolve()).catch(c => reject(c))
			} else if(data.transactionType === '1') {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const result = {}
						result.balance = (Number(obj.balance) - Number(data.amount)).toFixed(2)
						if(accountData.accountType === '3') {
							result.paidPrice = (Number(accountData.quotaUp) - result.balance).toFixed(2)
						}
						return unicloud.collection('account').where({ _id: data.accountId }).update(result)
					} else {
						reject('无支出账户信息')
					}
				}).then(() => resolve()).catch(c => reject(c))
			} else {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) - Number(data.amount)).toFixed(2)
						return unicloud.collection('account').where({ _id: data.accountId }).update({ balance })
					} else {
						reject('无支出账户信息')
					}
				}).then(res => {
					return unicloud.collection('account').where({ _id: data.refund }).get()
				}).then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) + Number(data.amount)).toFixed(2)
						const paidPrice = (Number(obj.quotaUp) - Number(balance)).toFixed(2)
						return unicloud.collection('account').where({ _id: data.accountId }).update({ balance, paidPrice })
					} else {
						reject('无还款账户信息')
					}
				})
				.then(() => resolve()).catch(c => reject(c))
			}
		})
	}
	
	/**
	 * 更新账单信息
	 * @param { number } _id 账户id
	 * @param { string } refund 还款账户
	 * @param { string } transactionType 收入: 0 支出: 1 还款: 2
	 * @param { number } amount 金额
	 * 收入: balance - amount
	 * 支出: balance + amount
	 * 还款: (支出账户: balance + amount) (还款账户: balance - amount  paidPrice + amount)
	*/
	const updateAccount = function (data, accountData) {
		return new Promise((resolve, reject) => {
			if(data.transactionType === '0') {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) + Number(data.amount)).toFixed(2)
						return unicloud.collection('account').where({ _id: data.accountId }).update({ balance })
					} else {
						reject('无支出账户信息')
					}
				}).then(() => resolve()).catch(c => reject(c))
			} else if(data.transactionType === '1') {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const result = {}
						result.balance = (Number(obj.balance) - Number(data.amount)).toFixed(2)
						if(accountData.accountType === '3') {
							result.paidPrice = (Number(accountData.quotaUp) - result.balance).toFixed(2)
						}
						return unicloud.collection('account').where({ _id: data.accountId }).update(result)
					} else {
						reject('无支出账户信息')
					}
				}).then(() => resolve()).catch(c => reject(c))
			} else {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) - Number(data.amount)).toFixed(2)
						return unicloud.collection('account').where({ _id: obj._id }).update({ balance })
					} else {
						reject('无支出账户信息')
					}
				}).then(res => {
					return unicloud.collection('account').where({ _id: data.refund }).get()
				}).then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) + Number(data.amount)).toFixed(2)
						const paidPrice = (Number(obj.quotaUp) - Number(balance)).toFixed(2)
						return unicloud.collection('account').where({ _id: obj._id }).update({ balance, paidPrice })
					} else {
						reject('无还款账户信息')
					}
				})
				.then(() => resolve()).catch(c => reject(c))
			}
		})
	}
	
	/**
	 * 移除账单信息
	 * @param { number } _id 账户id
	 * @param { string } refund 还款账户
	 * @param { string } transactionType 收入: 0 支出: 1 还款: 2
	 * @param { number } amount 金额
	 * 收入: balance - amount
	 * 支出: balance + amount
	 * 还款: (支出账户: balance + amount) (还款账户: balance - amount  paidPrice + amount)
	*/
	const removeAccount = function (data, accountData) {
		return new Promise((resolve, reject) => {
			if(data.transactionType === '0') {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) - Number(data.amount)).toFixed(2)
						return unicloud.collection('account').where({ _id: data.accountId }).update({ balance })
					} else {
						reject('无支出账户信息')
					}
				}).then(() => resolve()).catch(c => reject(c))
			} else if(data.transactionType === '1') {
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const result = {}
						result.balance = (Number(obj.balance) + Number(data.amount)).toFixed(2)
						if(accountData.accountType === '3') {
							result.paidPrice = (Number(accountData.quotaUp) - result.balance).toFixed(2)
						}
						return unicloud.collection('account').where({ _id: data.accountId }).update(result)
					} else {
						reject('无支出账户信息')
					}
				}).then(() => resolve()).catch(c => reject(c))
			} else{
				unicloud.collection('account').where({ _id: data.accountId }).get().then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) + Number(data.amount)).toFixed(2)
						return unicloud.collection('account').where({ _id: data.accountId }).update({ balance })
					} else {
						reject('无支出账户信息')
					}
				}).then(res => {
					return unicloud.collection('account').where({ _id: data.refund }).get()
				}).then(res => {
					if(res.data.length > 0) {
						const obj = res.data[0]
						const balance = (Number(obj.balance) - Number(data.amount)).toFixed(2)
						const paidPrice = (Number(obj.quotaUp) - Number(balance)).toFixed(2)
						return unicloud.collection('account').where({ _id: data.accountId }).update({ balance, paidPrice })
					} else {
						reject('无还款账户信息')
					}
				})
				.then(() => resolve()).catch(c => reject(c))
			}
		})
	}
	
	const excludeObject = function(arr, data, cb) {
		const obj = {}
		for (let key in data) {
			if(!arr.includes(key)) {
				obj[key] = data[key]
			}
			cb && typeof cb === 'function' && cb(key, data[key])
		}
		return obj
	}
	
	const captureCatch = function (c, reject) {
		console.log('captureCatch',c);
		reject(typeof c === 'string' ? { code: 500, msg: c } : c)
	}
	return {
		generateRandomString,
		parseTime,
		getTodayTimestamps,
		isCheckToken,
		addAccount,
		updateAccount,
		removeAccount,
		captureCatch,
		formatPrice,
		excludeObject
	}
}

module.exports = api()
